

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="https://img.mkerosene.cn/touxiang.jpg">
  <link rel="icon" href="https://img.mkerosene.cn/touxiang.jpg">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
    <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Kerosene W">
  <meta name="keywords" content="">
  
    <meta name="description" content="MySQL基础 SQL语句可以单行或多行书写，以分号结尾 MySQL数据库SQL语句不区分大小写，关键字建议大写 注释：单行-- 注释内容（空格）    或    #注释内容（MySQL特有） ​            多行&#x2F;*注释内容*&#x2F;  DDL(Data Definition Language)操作数据库 1.查询1SHOW databases;  2.创建 创建数据库  1CREATE d">
<meta property="og:type" content="article">
<meta property="og:title" content="MySQL_note">
<meta property="og:url" content="http://example.com/2021/11/21/MySQL%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/index.html">
<meta property="og:site_name" content="追求源于热爱">
<meta property="og:description" content="MySQL基础 SQL语句可以单行或多行书写，以分号结尾 MySQL数据库SQL语句不区分大小写，关键字建议大写 注释：单行-- 注释内容（空格）    或    #注释内容（MySQL特有） ​            多行&#x2F;*注释内容*&#x2F;  DDL(Data Definition Language)操作数据库 1.查询1SHOW databases;  2.创建 创建数据库  1CREATE d">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img.mkerosene.cn/4542e1b41694445278fc06b153cacc90.jpeg">
<meta property="article:published_time" content="2021-11-21T11:56:41.000Z">
<meta property="article:modified_time" content="2021-11-28T13:32:13.284Z">
<meta property="article:author" content="Kerosene W">
<meta property="article:tag" content="Mysql">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://img.mkerosene.cn/4542e1b41694445278fc06b153cacc90.jpeg">
  
  
  <title>MySQL_note - 追求源于热爱</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.8.13","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":"❡"},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"https://img.mkerosene.cn/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":"FI1uAFAYz0Q3MPDiORqd0JAN-gzGzoHsz","app_key":"EhKAjMe3bmq0WLTSgktGg2OC","server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
</head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>mKerosene</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/links/">
                <i class="iconfont icon-link-fill"></i>
                友链
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('https://img.mkerosene.cn/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="MySQL_note">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2021-11-21 19:56" pubdate>
        2021年11月21日 晚上
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      4k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      13 分钟
    </span>
  

  
  
    
      <!-- LeanCloud 统计文章PV -->
      <span id="leancloud-page-views-container" class="post-meta" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="leancloud-page-views"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">MySQL_note</h1>
            
              <p class="note note-info">
                
                  本文最后更新于：1 年前
                
              </p>
            
            <div class="markdown-body">
              <h1 id="MySQL基础"><a href="#MySQL基础" class="headerlink" title="MySQL基础"></a>MySQL基础</h1><blockquote>
<p>SQL语句可以单行或多行书写，以分号结尾</p>
<p>MySQL数据库SQL语句不区分大小写，关键字建议大写</p>
<p>注释：单行<code>-- 注释内容</code>（空格）    或    <code>#注释内容</code>（MySQL特有）</p>
<p>​            多行<code>/*注释内容*/</code></p>
</blockquote>
<h2 id="DDL-Data-Definition-Language"><a href="#DDL-Data-Definition-Language" class="headerlink" title="DDL(Data Definition Language)"></a>DDL(Data Definition Language)</h2><h3 id="操作数据库"><a href="#操作数据库" class="headerlink" title="操作数据库"></a>操作数据库</h3><hr>
<h4 id="1-查询"><a href="#1-查询" class="headerlink" title="1.查询"></a>1.查询</h4><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SHOW databases;<br></code></pre></td></tr></table></figure>

<h4 id="2-创建"><a href="#2-创建" class="headerlink" title="2.创建"></a>2.创建</h4><ul>
<li>创建数据库</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">CREATE database 数据库名称;<br></code></pre></td></tr></table></figure>

<ul>
<li>创建数据库（判断，如果不存在则创建）</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">CREATE database IF NOT EXISTS 数据库名称;<br></code></pre></td></tr></table></figure>

<h4 id="3-删除"><a href="#3-删除" class="headerlink" title="3.删除"></a>3.删除</h4><ul>
<li>删除数据库</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">DROP database 数据库名称;<br></code></pre></td></tr></table></figure>

<ul>
<li>删除数据库（判断，如果存在则删除）</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">DROP database IF EXISTS 数据库名称;<br></code></pre></td></tr></table></figure>

<h4 id="4-使用数据库"><a href="#4-使用数据库" class="headerlink" title="4.使用数据库"></a>4.使用数据库</h4><ul>
<li>查看当前使用的数据库</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT database();<br></code></pre></td></tr></table></figure>

<ul>
<li>使用数据库</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">USE 数据库名称;<br></code></pre></td></tr></table></figure>

<h3 id="操作表"><a href="#操作表" class="headerlink" title="操作表"></a>操作表</h3><hr>
<h4 id="1-查询表"><a href="#1-查询表" class="headerlink" title="1.查询表"></a>1.查询表</h4><ul>
<li>查询当前数据库下所有表名称</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SHOW tables;<br></code></pre></td></tr></table></figure>

<ul>
<li>查询表结构</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">DESC 表名称;<br></code></pre></td></tr></table></figure>

<h4 id="2-创建表"><a href="#2-创建表" class="headerlink" title="2.创建表"></a>2.创建表</h4><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs mysql">CREATE 表名 (<br>字段名1 数据类型1,<br>字段名2 数据类型2,<br>···<br>字段名n 数据类型n<br>);	#最后一行末尾不加逗号<br></code></pre></td></tr></table></figure>

<h4 id="数据类型"><a href="#数据类型" class="headerlink" title="数据类型"></a>数据类型</h4><table>
<thead>
<tr>
<th>数据类型</th>
<th>大小</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>TINYINT</td>
<td>1 byte</td>
<td>小整数值</td>
</tr>
<tr>
<td>SMALLINT</td>
<td>2 bytes</td>
<td>大整数值</td>
</tr>
<tr>
<td>MEDIUMINT</td>
<td>3 bytes</td>
<td>大整数值</td>
</tr>
<tr>
<td>INT或INTEGER</td>
<td>4 bytes</td>
<td>大整数值</td>
</tr>
<tr>
<td>BIGINT</td>
<td>8 bytes</td>
<td>极大整数值</td>
</tr>
<tr>
<td>FLOAT</td>
<td>4 bytes</td>
<td>单精度浮点数值</td>
</tr>
<tr>
<td>DOUBLE</td>
<td>8 bytes</td>
<td>双精度浮点数值</td>
</tr>
<tr>
<td>DECIMAL</td>
<td></td>
<td>小数值</td>
</tr>
<tr>
<td>DATE</td>
<td>3</td>
<td>日期值</td>
</tr>
<tr>
<td>TIME</td>
<td>3</td>
<td>时间值或持续时间</td>
</tr>
<tr>
<td>YEAR</td>
<td>1</td>
<td>年份值</td>
</tr>
<tr>
<td>DATETIME</td>
<td>8</td>
<td>混合日期和时间值</td>
</tr>
<tr>
<td>TIMESTAMP</td>
<td>4</td>
<td>混合日期和时间值，时间戳</td>
</tr>
<tr>
<td>CHAR</td>
<td>0-255 bytes</td>
<td>定长字符串</td>
</tr>
<tr>
<td>VARCHAR</td>
<td>0-65535 bytes</td>
<td>变长字符串</td>
</tr>
<tr>
<td>TINYBLOB</td>
<td>0-255 bytes</td>
<td>不超过 255 个字符的二进制字符串</td>
</tr>
<tr>
<td>TINYTEXT</td>
<td>0-255 bytes</td>
<td>短文本字符串</td>
</tr>
<tr>
<td>BLOB</td>
<td>0-65 535 bytes</td>
<td>二进制形式的长文本数据</td>
</tr>
<tr>
<td>TEXT</td>
<td>0-65 535 bytes</td>
<td>长文本数据</td>
</tr>
<tr>
<td>MEDIUMBLOB</td>
<td>0-16 777 215 bytes</td>
<td>二进制形式的中等长度文本数据</td>
</tr>
<tr>
<td>MEDIUMTEXT</td>
<td>0-16 777 215 bytes</td>
<td>中等长度文本数据</td>
</tr>
<tr>
<td>LONGBLOB</td>
<td>0-4 294 967 295 bytes</td>
<td>二进制形式的极大文本数据</td>
</tr>
<tr>
<td>LONGTEXT</td>
<td>0-4 294 967 295 bytes</td>
<td>极大文本数据</td>
</tr>
</tbody></table>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs mysql">age int<br>score double(总长度,小数点后保留位数)<br>birthday date<br>name char(大小)		存储性能高，浪费空间<br>name varchar(大小)	存储性能低，节约空间<br></code></pre></td></tr></table></figure>

<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs mysql">#练习<br>create table student(<br><br>id int,<br><br>name varchar(10),<br><br>gender char(1),<br><br>birthday date,<br><br>score double(5,2),<br><br>email varchar(64),<br><br>tel varchar(15),<br><br>status tinyint<br><br>);<br><br></code></pre></td></tr></table></figure>

<h4 id="3-删除表"><a href="#3-删除表" class="headerlink" title="3.删除表"></a>3.删除表</h4><ul>
<li>删除表</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">DROP table 表名;<br></code></pre></td></tr></table></figure>

<ul>
<li>删除表时判断·表是否存在</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">DROP table IF EXISTS 表名;<br></code></pre></td></tr></table></figure>

<h4 id="4-修改表"><a href="#4-修改表" class="headerlink" title="4.修改表"></a>4.修改表</h4><ul>
<li>修改表名</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">ALTER table 表名 RENAME TO 新表名;<br></code></pre></td></tr></table></figure>

<ul>
<li>添加一列</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">ALTER table 表名 ADD 列名 数据类型;<br></code></pre></td></tr></table></figure>

<ul>
<li>修改数据类型</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">ALTER table 表名 MODIFY 列名 新数据类型;<br></code></pre></td></tr></table></figure>

<ul>
<li>修改列名和数据类型</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">ALTER table 表名 change 列名 新列名 新数据类型;<br></code></pre></td></tr></table></figure>

<ul>
<li>删除列</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">ALTER table 表名 DROP 列名;<br></code></pre></td></tr></table></figure>

<h2 id="DML-Data-Manipulation-Language"><a href="#DML-Data-Manipulation-Language" class="headerlink" title="DML(Data Manipulation Language)"></a>DML(Data Manipulation Language)</h2><h4 id="1-添加数据"><a href="#1-添加数据" class="headerlink" title="1.添加数据"></a>1.添加数据</h4><ul>
<li>给指定列添加数据</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">INSERT INTO 表名(列名1,列名2,...) values(值1,值2,...);<br></code></pre></td></tr></table></figure>

<ul>
<li>给全部列添加数据</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">INSERT INTO values(值1,值2,...);<br></code></pre></td></tr></table></figure>

<ul>
<li>批量添加数据</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs mysql">INSERT INTO 表名(列名1,列名2,...) values(值1,值2,...),(值1,值2,...),(值1,值2,...)...;<br>INSERT INTO values(值1,值2,...),(值1,值2,...),(值1,值2,...)...;<br></code></pre></td></tr></table></figure>

<h4 id="2-修改数据"><a href="#2-修改数据" class="headerlink" title="2.修改数据"></a>2.修改数据</h4><ul>
<li>修改表数据</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">UPDATE 表名 SET 列名1=值1,列名2=值2,...[where 条件];<br></code></pre></td></tr></table></figure>

<h4 id="3-删除数据"><a href="#3-删除数据" class="headerlink" title="3.删除数据"></a>3.删除数据</h4><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">DELETE FROM 表名 [WHERE 条件];<br></code></pre></td></tr></table></figure>

<blockquote>
<p>修改和删除如果不加条件则是对表全部数据做处理！</p>
</blockquote>
<h2 id="DQL-Data-Query-Language"><a href="#DQL-Data-Query-Language" class="headerlink" title="DQL(Data Query Language)"></a>DQL(Data Query Language)</h2><h3 id="基础查询"><a href="#基础查询" class="headerlink" title="基础查询"></a>基础查询</h3><h4 id="1-查询多个字段"><a href="#1-查询多个字段" class="headerlink" title="1.查询多个字段"></a>1.查询多个字段</h4><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT 字段(列名)列表 FROM 表名;<br>SELECT * FROM 表名; -- 查询所有数据<br></code></pre></td></tr></table></figure>

<h4 id="2-去除重复记录"><a href="#2-去除重复记录" class="headerlink" title="2.去除重复记录"></a>2.去除重复记录</h4><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT DISTINCT 字段(列名)列表 FROM 表名;<br></code></pre></td></tr></table></figure>

<h4 id="3-起别名"><a href="#3-起别名" class="headerlink" title="3.起别名"></a>3.起别名</h4><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">AS 可省略，一个空格代替<br></code></pre></td></tr></table></figure>

<h3 id="条件查询"><a href="#条件查询" class="headerlink" title="条件查询"></a>条件查询</h3><h4 id="1-语法"><a href="#1-语法" class="headerlink" title="1.语法"></a>1.语法</h4><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT 字段(列名)列表 FROM 表名 WHERE 条件列表;<br></code></pre></td></tr></table></figure>

<h4 id="2-条件"><a href="#2-条件" class="headerlink" title="2.条件"></a>2.条件</h4><table>
<thead>
<tr>
<th>符号</th>
<th>功能</th>
</tr>
</thead>
<tbody><tr>
<td>&gt;</td>
<td>大于</td>
</tr>
<tr>
<td>&lt;</td>
<td>小于</td>
</tr>
<tr>
<td>&gt;=</td>
<td>大于等于</td>
</tr>
<tr>
<td>&lt;=</td>
<td>小于等于</td>
</tr>
<tr>
<td>=</td>
<td>等于</td>
</tr>
<tr>
<td>&lt;&gt; 或 !=</td>
<td>不等于</td>
</tr>
<tr>
<td>BETWEEN…AND…</td>
<td>在某个范围内（含边界）</td>
</tr>
<tr>
<td>IN(…)</td>
<td>多选一</td>
</tr>
<tr>
<td>LIKE 占位符</td>
<td>模糊查询_单个%多个任意字符</td>
</tr>
<tr>
<td>IS NULL</td>
<td>是NULL</td>
</tr>
<tr>
<td>IS NOT NULL</td>
<td>不是NULL</td>
</tr>
<tr>
<td>AND 或 &amp;&amp;</td>
<td>并且</td>
</tr>
<tr>
<td>OR 或 ||</td>
<td>或者</td>
</tr>
<tr>
<td>NOT 或 !</td>
<td>非，不是</td>
</tr>
</tbody></table>
<h3 id="排序查询"><a href="#排序查询" class="headerlink" title="排序查询"></a>排序查询</h3><h4 id="1-语法-1"><a href="#1-语法-1" class="headerlink" title="1.语法"></a>1.语法</h4><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT 字段列表 FROM 表名 ORDER BY 排序字段名1[排序方式1],排序字段名2[排序方式2]...;<br></code></pre></td></tr></table></figure>

<ul>
<li>排序方式：<ul>
<li>ASC：升序（default）</li>
<li>DESC：降序</li>
</ul>
</li>
</ul>
<blockquote>
<p>多个排序条件下，前一排序结果相同，再进行下一排序</p>
</blockquote>
<h3 id="分组查询"><a href="#分组查询" class="headerlink" title="分组查询"></a>分组查询</h3><h4 id="聚合函数"><a href="#聚合函数" class="headerlink" title="聚合函数"></a>聚合函数</h4><ul>
<li>概念：将一列数据作为一个整体，进行纵向计算。</li>
<li>分类：<ul>
<li>count(列名)，统计数量（选取非null列）</li>
<li>max(列名)，最大值</li>
<li>min(列名)，最小值</li>
<li>sum(列名)，求和</li>
<li>avg(列名)，平均值</li>
</ul>
</li>
<li>语法：</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT 聚合函数名(列名) FROM 表;<br></code></pre></td></tr></table></figure>

<blockquote>
<p>null值不参与聚合函数的运算</p>
</blockquote>
<h4 id="1-语法-2"><a href="#1-语法-2" class="headerlink" title="1.语法"></a>1.语法</h4><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT 字段列表 FROM 表名 [WHERE 分组前限定条件] GROUP BY 分组字段名 [HAVING 分组后条件过滤];<br></code></pre></td></tr></table></figure>

<ul>
<li>where和having区别：<ul>
<li>执行时机不一样，分别为分组前后</li>
<li>可判断条件不同：where不能对聚合函数判断</li>
<li>where &gt; 聚合函数 &gt; having</li>
</ul>
</li>
</ul>
<h3 id="分页查询"><a href="#分页查询" class="headerlink" title="分页查询"></a>分页查询</h3><h4 id="1-语法-3"><a href="#1-语法-3" class="headerlink" title="1.语法"></a>1.语法</h4><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT 字段列表 FROM 表名 LIMIT 起始索引 , 查询条目;<br></code></pre></td></tr></table></figure>

<blockquote>
<p>起始索引 = （当前页码-1）* 每页显示条目</p>
</blockquote>
<h1 id="MySQL高级"><a href="#MySQL高级" class="headerlink" title="MySQL高级"></a>MySQL高级</h1><h2 id="约束"><a href="#约束" class="headerlink" title="约束"></a>约束</h2><blockquote>
<p>从数据库层面在添加数据的时候进行限制</p>
</blockquote>
<h3 id="分类"><a href="#分类" class="headerlink" title="分类"></a>分类</h3><table>
<thead>
<tr>
<th>约束名称</th>
<th>描述</th>
<th>关键字</th>
</tr>
</thead>
<tbody><tr>
<td>非空约束</td>
<td>保证列中所有的数据不能有null值</td>
<td>NOT NULL</td>
</tr>
<tr>
<td>唯一约束</td>
<td>保证列中所有数据各不相同</td>
<td>UNIQUE</td>
</tr>
<tr>
<td>主键约束</td>
<td>主键是一行数据的唯一标识，要求非空且唯一</td>
<td>PRIMARY KEY</td>
</tr>
<tr>
<td>检查约束</td>
<td>保证列中的值满足某一条件</td>
<td>CHECK</td>
</tr>
<tr>
<td>默认约束</td>
<td>保存数据时，未指定值则采用默认值</td>
<td>DEFAULT</td>
</tr>
<tr>
<td>外键约束</td>
<td>两个表的数据建立链接，保证数据的一致完整性</td>
<td>FOREIGN KEY</td>
</tr>
</tbody></table>
<blockquote>
<p>Mysql不支持检查约束</p>
</blockquote>
<ul>
<li><p>语法</p>
<ul>
<li><p>添加约束</p>
 <figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs sql"><span class="hljs-comment">-- 创建表时添加默认约束</span><br><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> 表名(<br>   列名 数据类型 <span class="hljs-keyword">DEFAULT</span> 默认值,<br>   …<br>);<br></code></pre></td></tr></table></figure>

<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs sql"><span class="hljs-comment">-- 建完表后添加默认约束</span><br><span class="hljs-keyword">ALTER</span> <span class="hljs-keyword">TABLE</span> 表名 <span class="hljs-keyword">ALTER</span> 列名 <span class="hljs-keyword">SET</span> <span class="hljs-keyword">DEFAULT</span> 默认值;<br></code></pre></td></tr></table></figure></li>
</ul>
<ul>
<li>删除约束</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">ALTER TABLE 表名 ALTER 列名 DROP DEFAULT;<br></code></pre></td></tr></table></figure></li>
<li><p>使用实例</p>
</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs mysql">-- 员工表<br>CREATE TABLE emp (<br>  id INT PRIMARY KEY auto_increment, -- 员工id，主键且自增长<br>  ename VARCHAR(50) NOT NULL UNIQUE, -- 员工姓名，非空并且唯一<br>  joindate DATE NOT NULL , -- 入职日期，非空<br>  salary DOUBLE(7,2) NOT NULL , -- 工资，非空<br>  bonus DOUBLE(7,2) DEFAULT 0 -- 奖金，如果没有奖金默认为0<br>);<br></code></pre></td></tr></table></figure>

<blockquote>
<p>自增长： auto_increment  当列是数字类型并且唯一约束</p>
</blockquote>
<h3 id="外键约束"><a href="#外键约束" class="headerlink" title="外键约束"></a>外键约束</h3><ul>
<li>添加外键约束</li>
</ul>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs sql"><span class="hljs-comment">-- 创建表时添加外键约束</span><br><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> 表名(<br>   列名 数据类型,<br>   …<br>   [<span class="hljs-keyword">CONSTRAINT</span>] [外键名称] <span class="hljs-keyword">FOREIGN</span> KEY(外键列名) <span class="hljs-keyword">REFERENCES</span> 主表(主表列名) <br>); <br></code></pre></td></tr></table></figure>

<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs sql"><span class="hljs-comment">-- 建完表后添加外键约束</span><br><span class="hljs-keyword">ALTER</span> <span class="hljs-keyword">TABLE</span> 表名 <span class="hljs-keyword">ADD</span> <span class="hljs-keyword">CONSTRAINT</span> 外键名称 <span class="hljs-keyword">FOREIGN</span> KEY (外键字段名称) <span class="hljs-keyword">REFERENCES</span> 主表名称(主表列名称);<br></code></pre></td></tr></table></figure>

<ul>
<li>删除外键约束</li>
</ul>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs sql"><span class="hljs-keyword">ALTER</span> <span class="hljs-keyword">TABLE</span> 表名 <span class="hljs-keyword">DROP</span> <span class="hljs-keyword">FOREIGN</span> KEY 外键名称;<br></code></pre></td></tr></table></figure>

<h3 id="多表查询"><a href="#多表查询" class="headerlink" title="多表查询"></a>多表查询</h3><h4 id="1-连接查询"><a href="#1-连接查询" class="headerlink" title="1.连接查询"></a>1.连接查询</h4><ul>
<li>内连接</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs mysql">#隐式内连接<br>SELECT 字段列表 FROM 表1,表2… WHERE 条件;<br>#显示内连接<br>SELECT 字段列表 FROM 表1 [INNER] JOIN 表2 ON 条件;<br></code></pre></td></tr></table></figure>

<blockquote>
<p>A、B集合交集</p>
</blockquote>
<ul>
<li>外连接</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs mysql">#左外连接：A集合+交集部分<br>SELECT 字段列表 FROM 表1 LEFT [OUTER] JOIN 表2 ON 条件;<br>#右外连接：交集部分+B集合<br>SELECT 字段列表 FROM 表1 RIGHT [OUTER] JOIN 表2 ON 条件;<br></code></pre></td></tr></table></figure>

<ul>
<li><p>子查询</p>
<ul>
<li>单行单列：作为条件值，使用=、!=、&gt;、&lt;等条件判断</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT 字段列表 FROM 表 WHERE 字段名 = (子查询);<br></code></pre></td></tr></table></figure>

<ul>
<li>多行单列：作为条件值，使用in等关键字进行条件判断</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT 字段列表 FROM 表 WHERE 字段名 in (子查询);<br></code></pre></td></tr></table></figure>

<ul>
<li>多行多列：作为虚拟表</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">SELECT 字段列表 FROM (z) WHERE 条件;<br></code></pre></td></tr></table></figure></li>
</ul>
<h2 id="事务"><a href="#事务" class="headerlink" title="事务"></a>事务</h2><ul>
<li>一组数据库操作命令，同时成功或失败</li>
</ul>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs sql">#开启事务<br><span class="hljs-keyword">START</span> TRANSACTION;或<span class="hljs-keyword">BEGIN</span>;<br>#回滚事务<br><span class="hljs-keyword">ROLLBACK</span>;<br>#提交事务<br><span class="hljs-keyword">COMMIT</span>;<br></code></pre></td></tr></table></figure>

<ul>
<li>Mysql默认自动提交事务</li>
</ul>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs sql">#查看事务默认提交方式<br><span class="hljs-keyword">SELECT</span> @<span class="hljs-variable">@autocommit</span>;<br><span class="hljs-comment">-- 1-&gt;自动提交，2-&gt;手动提交</span><br>#修改提交方式<br><span class="hljs-keyword">set</span> @<span class="hljs-variable">@autocommit</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;<br></code></pre></td></tr></table></figure>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/note/">note</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/Mysql/">Mysql</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2021/11/28/JDBC%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">JDBC</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2021/10/27/%E8%AE%A1%E7%AE%97%E6%9C%BA%E6%95%99%E8%82%B2%E4%B8%AD%E7%BC%BA%E5%A4%B1%E7%9A%84%E4%B8%80%E8%AF%BE(%E4%BA%8C)/">
                        <span class="hidden-mobile">计算机教育中缺失的一课(二)</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
              <!-- Comments -->
              <article class="comments" id="comments" lazyload>
                
                  
                
                
  <div id="twikoo"></div>
  <script type="text/javascript">
    Fluid.utils.loadComments('#comments', function() {
      Fluid.utils.createScript('https://cdn.jsdelivr.net/npm/twikoo@1/dist/twikoo.all.min.js', function() {
        var options = Object.assign(
          {"envId":"blog-3gentarg3e6a1b5e","region":"ap-shanghai","path":"window.location.pathname"},
          {
            el: '#twikoo',
            path: 'window.location.pathname',
            onCommentLoaded: function() {
              Fluid.plugins.initFancyBox('#twikoo .tk-content img:not(.tk-owo-emotion)');
            }
          }
        )
        twikoo.init(options)
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


              </article>
            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <div class="copyright">&copy;2020 - 2021 By Kerosene.W</div> <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
  </div>
  
  <div class="statistics">
    
    

    
      
        <!-- LeanCloud 统计PV -->
        <span id="leancloud-site-pv-container" style="display: none">
            总访问量 
            <span id="leancloud-site-pv"></span>
             次
          </span>
      
      
        <!-- LeanCloud 统计UV -->
        <span id="leancloud-site-uv-container" style="display: none">
            总访客数 
            <span id="leancloud-site-uv"></span>
             人
          </span>
      

    
  </div>


  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  




  <script defer src="/js/leancloud.js" ></script>



  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
        typing(title);
      
    })(window, document);
  </script>












  

  

  

  

  

  





<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
